import React, { useEffect, useRef, useState } from 'react';
import { NavigationProps } from '../index';
import styles from './index.module.scss';
import Hamburger from '@/assets/icons/hamburger.svg?react';
import classNames from 'classnames';
import Popup from '@base/components/Popup';
import Menu from '../../Menu';

const MobileNavigation: React.FC<NavigationProps> = ({ categorys }) => {

    const [activeIndex, setActiveIndex] = useState(0);

    const itemRefs = useRef<HTMLLIElement[]>([]);

    const navRef = useRef<HTMLUListElement>(null);

    const [sliderStyle, setSliderStyle] = useState({transform: 'translateX(3px)', width: '50px', height: '28px'});

    const [showPopup, setShowPopup] = useState(false);

    const clickByMenuRef = useRef(false);

    useEffect(() => {
      if (itemRefs.current.length === 0) {
        return;
      }

      // 获取点击的item的宽度、距离屏幕左侧位置，以及navigation的水平滚动距离
      const activeItem = itemRefs.current[activeIndex];
      const {left, width, height} = activeItem.getBoundingClientRect();
      const {scrollLeft = 0} = navRef.current!;

      // 更新滑块的移动距离与宽度
      setSliderStyle({
        transform: `translateX(${left + scrollLeft}px)`,
        width: `${width}px`,
        height: `${height}px`,
      })

      // 如果是通过Menu组件点击的item，则还要更新navigation的水平滚动距离
      if (clickByMenuRef.current) {
        const offsetLeft = activeItem.offsetLeft;
        navRef.current!.scrollLeft = offsetLeft;
        clickByMenuRef.current = false;
      }
        
    }, [activeIndex])

    function handleClickItem(index: number) {
      setActiveIndex(index);
    }

    function handleClickIcon() {
      setShowPopup(true);
    }

    function handleClickMenuItem(index: number) {
      handleClickItem(index);
      setShowPopup(false);
      clickByMenuRef.current = true;
    }

    return (
        <div className={styles.container}>
            <Popup open={showPopup} onClose={() => setShowPopup(false)}>
              <Menu categorys={categorys} onSelect={handleClickMenuItem}/>
            </Popup>
            <ul className={styles.navigation} ref={navRef}>
                {/* 汉堡按钮 */}
                <li className={styles['item-icon']} onClick={handleClickIcon}>
                    <Hamburger className={styles.icon} />
                </li>
                {/* 滑块 */}
                <li 
                  className={styles.slider} 
                  style={sliderStyle}
                />
                {/* 分类项 */}
                {categorys?.map((item, index) => {
                    const classes = classNames(styles.item, {
                      [styles['active']]: activeIndex === index,
                    });

                    return (
                        <li 
                          key={item.id} 
                          className={classes} 
                          ref={(el) => {
                            if (el) {
                              itemRefs.current[index] = el
                            }
                          }}
                          onClick={() => handleClickItem(index)}
                        >
                            {item.name}
                        </li>
                    );
                })}
            </ul>
        </div>
    );
};

export default MobileNavigation;
